# -*- coding: utf-8 -*-
"""
主窗口模块
实现应用程序的主窗口界面，包含菜单栏和主要布局
"""

import sys
from PySide2.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QMenuBar, QMenu, QAction,
    QApplication, QStatusBar
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QIcon

from gglobal import logger, config
from mooetoolapp.handlercore.theme_manager import ThemeManager
from mooetoolapp.handlercore.language_manager import LanguageManager
from mooetoolapp.views.windows_setting import SettingsWindow
from mooetoolapp.handlercore.imagesource import qInitResources



class MainWindow(QMainWindow):
    """
    应用程序主窗口类
    包含菜单栏、工具栏和主要内容区域
    """
    
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.settings_window = None
        # 初始化资源
        qInitResources()
        self.init_managers()
        self.init_ui()
        self.setup_connections()
        self.apply_initial_theme()
        
    def init_managers(self):
        """初始化管理器"""
        # 初始化主题管理器
        import os
        project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        qss_folder = os.path.join(project_root, "resource", "qss")
        self.theme_manager = ThemeManager(qss_folder, self)
        
        # 初始化语言管理器
        self.language_manager = LanguageManager(self)
        
        logger.info("管理器初始化完成")
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("MooeTool")
        self.setMinimumSize(800, 600)
        
        # 设置窗口图标
        try:
            window_icon = QIcon(":/icon/tool.svg")
            self.setWindowIcon(window_icon)
            logger.info("窗口图标设置成功")
        except Exception as e:
            logger.error(f"窗口图标设置失败: {e}")
        
        # 创建中央控件和主布局
        central_widget = QWidget()
        central_widget.setObjectName("main_widget")  # 设置对象名称以匹配CSS样式
        self.setCentralWidget(central_widget)
        
        # 创建垂直布局
        self.main_layout = QVBoxLayout(central_widget)
        self.main_layout.setContentsMargins(10, 10, 10, 10)
        self.main_layout.setSpacing(10)
        
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")
        
        logger.info("主窗口UI初始化完成")
        
    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 视图菜单
        self.view_menu = menubar.addMenu("视图(&V)")
        
        # 主题切换子菜单
        self.theme_menu = self.view_menu.addMenu("主题")
        
        # 动态创建主题菜单项
        self.theme_actions = {}
        self.create_theme_menu_items()
        
        self.view_menu.addSeparator()
        
        # 语言设置子菜单
        self.language_menu = self.view_menu.addMenu("语言")
        
        # 中文
        self.chinese_action = QAction("中文", self)
        self.chinese_action.setCheckable(True)
        self.chinese_action.setChecked(True)  # 默认选中中文
        self.chinese_action.triggered.connect(lambda: self.change_language("zh_CN"))
        self.language_menu.addAction(self.chinese_action)
        
        # English
        self.english_action = QAction("English", self)
        self.english_action.setCheckable(True)
        self.english_action.triggered.connect(lambda: self.change_language("en_US"))
        self.language_menu.addAction(self.english_action)
        
        # 设置菜单
        self.settings_menu = menubar.addMenu("设置(&S)")
        
        # 系统设置
        self.system_settings_action = QAction("系统设置", self)
        self.system_settings_action.triggered.connect(self.open_settings)
        self.settings_menu.addAction(self.system_settings_action)
        
        # 注册菜单到语言管理器
        self.register_menu_widgets()
        
        logger.info("菜单栏创建完成")
        
    def create_theme_menu_items(self):
        """动态创建主题菜单项"""
        try:
            # 获取所有可用主题
            available_themes = self.theme_manager.get_available_themes()
            current_theme = self.theme_manager.get_current_theme_name()
            
            # 为每个主题创建菜单项
            for theme_name in available_themes:
                action = QAction(theme_name, self)
                action.setCheckable(True)
                
                # 设置当前主题为选中状态
                if theme_name == current_theme:
                    action.setChecked(True)
                
                # 连接信号
                action.triggered.connect(lambda checked=False, name=theme_name: self.change_theme(name))
                
                # 添加到菜单和字典
                self.theme_menu.addAction(action)
                self.theme_actions[theme_name] = action
                
            logger.info(f"动态创建了 {len(available_themes)} 个主题菜单项: {available_themes}")
        except Exception as e:
            logger.error(f"创建主题菜单项失败: {e}")
            # 如果动态创建失败，创建默认主题
            self._create_default_theme_items()
            
    def _create_default_theme_items(self):
        """创建默认主题菜单项（fallback）"""
        default_themes = ["light", "dark"]
        for theme_name in default_themes:
            action = QAction(theme_name, self)
            action.setCheckable(True)
            if theme_name == "light":
                action.setChecked(True)
            action.triggered.connect(lambda checked=False, name=theme_name: self.change_theme(name))
            self.theme_menu.addAction(action)
            self.theme_actions[theme_name] = action
        logger.info("创建了默认主题菜单项")
        
    def setup_connections(self):
        """设置信号连接"""
        # 连接主题管理器信号
        self.theme_manager.theme_changed.connect(self.on_theme_changed)
        
        # 连接语言管理器信号
        self.language_manager.language_changed.connect(self.on_language_changed)
        
    def register_menu_widgets(self):
        """注册菜单控件到语言管理器"""
        try:
            # 注册菜单标题
            self.language_manager.register_widget(self.view_menu, "view_menu_title", "title")
            self.language_manager.register_widget(self.theme_menu, "theme_menu_title", "title")
            self.language_manager.register_widget(self.language_menu, "language_menu_title", "title")
            self.language_manager.register_widget(self.settings_menu, "settings_menu_title", "title")
            
            # 注册菜单项文本
            self.language_manager.register_widget(self.system_settings_action, "system_settings_action")
            
            logger.info("主窗口菜单控件注册完成")
        except Exception as e:
            logger.error(f"注册主窗口菜单控件失败: {e}")
        
    def apply_initial_theme(self):
        """应用初始主题"""
        try:
            initial_data = self.theme_manager.get_initial_theme_data()
            qss_content = initial_data.get("qss_content", "")
            constants = initial_data.get("constants", {})
            
            if qss_content:
                self.setStyleSheet(qss_content)
                logger.info("初始主题应用成功")
            
            # 应用窗口大小设置
            self._apply_window_size_from_theme(constants)
        except Exception as e:
            logger.error(f"应用初始主题失败: {e}")
            
    def change_theme(self, theme_name):
        """切换主题"""
        try:
            self.theme_manager.apply_theme(theme_name)
            
            # 更新所有主题菜单项的选中状态
            for name, action in self.theme_actions.items():
                action.setChecked(name == theme_name)
                
            logger.info(f"主题切换为: {theme_name}")
        except Exception as e:
            logger.error(f"主题切换失败: {e}")
            
    def change_language(self, language_code):
        """切换语言"""
        try:
            self.language_manager.set_language(language_code)
            config.set_param("current_language", language_code)
            
            # 更新语言菜单项的选中状态（去除黑点，只使用setChecked）
            if language_code == "zh_CN":
                self.chinese_action.setChecked(True)
                self.english_action.setChecked(False)
            elif language_code == "en_US":
                self.chinese_action.setChecked(False)
                self.english_action.setChecked(True)
                
            logger.info(f"语言切换为: {language_code}")
        except Exception as e:
            logger.error(f"语言切换失败: {e}")
            
    def open_settings(self):
        """打开设置窗口"""
        if self.settings_window is None:
            self.settings_window = SettingsWindow(self)
        self.settings_window.show()
        self.settings_window.raise_()
        self.settings_window.activateWindow()
        
    def on_theme_changed(self, qss_content):
        """主题改变时的处理"""
        self.setStyleSheet(qss_content)
        self.status_bar.showMessage("主题已更新", 2000)
        
        # 获取当前主题的常量并应用窗口大小
        try:
            constants = self.theme_manager.get_theme_constants()
            self._apply_window_size_from_theme(constants)
        except Exception as e:
            logger.error(f"应用主题窗口大小失败: {e}")
        
    def _apply_window_size_from_theme(self, constants: dict):
        """从主题常量中应用窗口大小设置"""
        try:
            if "windows_size" in constants:
                window_size = constants["windows_size"]
                if isinstance(window_size, list) and len(window_size) == 2:
                    width, height = window_size
                    self.resize(width, height)
                    logger.info(f"已从主题设置窗口大小为: {width}x{height}")
                else:
                    logger.warning(f"主题中的窗口大小格式无效: {window_size}")
            else:
                logger.info("主题中未找到窗口大小设置，使用默认大小")
        except Exception as e:
            logger.error(f"应用主题窗口大小失败: {e}")
    
    def on_language_changed(self, language_data):
        """语言改变时的处理"""
        # 这里可以更新界面文本
        self.status_bar.showMessage("语言已更新", 2000)
        
    def get_main_layout(self):
        """获取主布局，供其他模块使用"""
        return self.main_layout
        
    def closeEvent(self, event):
        """窗口关闭事件"""
        logger.info("主窗口关闭")
        event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())